package com.ostrich.cloud.ostrichOrderService.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ostrich.cloud.common.exceptions.OstrichException;
import com.ostrich.cloud.common.result.PageResult;
import com.ostrich.cloud.common.result.Result;
import com.ostrich.cloud.ostrichDistributionService.client.DeliveryOrderClient;
import com.ostrich.cloud.ostrichDistributionService.client.param.OrderParam;
import com.ostrich.cloud.ostrichGoodsSercice.model.Dto.GoodsDto;
import com.ostrich.cloud.ostrichGoodsSercice.model.param.AddSalesParam;
import com.ostrich.cloud.ostrichGoodsSercice.model.param.PutGoodsParam;
import com.ostrich.cloud.ostrichGoodsService.client.GoodsClient;
import com.ostrich.cloud.ostrichGoodsService.client.SalesClient;
import com.ostrich.cloud.ostrichGoodsService.client.SecKillClient;
import com.ostrich.cloud.ostrichOrderService.common.OstrichOrderServiceResultCode;
import com.ostrich.cloud.ostrichOrderService.infra.mapper.OrderInfoMapper;
import com.ostrich.cloud.ostrichOrderService.infra.mapper.ShoppingCarGoodsMapper;
import com.ostrich.cloud.ostrichOrderService.infra.mapper.ShoppingCarMapper;
import com.ostrich.cloud.ostrichOrderService.infra.model.Order1;
import com.ostrich.cloud.ostrichOrderService.infra.mapper.Order1Mapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ostrich.cloud.ostrichOrderService.infra.model.OrderInfo;
import com.ostrich.cloud.ostrichOrderService.infra.model.ShoppingCar;
import com.ostrich.cloud.ostrichOrderService.infra.model.ShoppingCarGoods;
import com.ostrich.cloud.ostrichOrderService.infra.param.*;
import com.ostrich.cloud.ostrichOrderService.model.dto.*;
import com.ostrich.cloud.ostrichOrderService.service.service.Order1Service;
import com.ostrich.cloud.ostrichUserService.client.CustomerMangerClient;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;


import javax.annotation.Resource;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2022-10-26
 */
@Service
@Slf4j
@GlobalTransactional(rollbackFor = Exception.class)
public class Order1ServiceImpl extends ServiceImpl<Order1Mapper, Order1> implements Order1Service {
    @Resource
    private Order1Mapper orderMapper;
    @Resource
    private OrderInfoMapper orderInfoMapper;
    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private GoodsClient goodsClient;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private ShoppingCarMapper shoppingCarMapper;
    @Resource
    private ShoppingCarGoodsMapper shoppingCarGoodsMapper;
    @Resource
    private CustomerMangerClient customerMangerClient;
    @Resource
    private  DeliveryOrderClient deliveryOrderClient;
    @Resource
    private SalesClient salesClient;
    @Resource
    private SecKillClient secKillClient;


    @Override
    public void CreateOrder(CreateParamInfra param) throws TransactionException {
        try {
            if (param.getCouponId()!=0){
                // todo 优惠卷
            }
            QueryWrapper<ShoppingCar> carQueryWrapper = new QueryWrapper<>();
            carQueryWrapper.eq("customer_id",param.getCustomerId());
            ShoppingCar shoppingCar = shoppingCarMapper.selectOne(carQueryWrapper);
            QueryWrapper<ShoppingCarGoods> carGoodsQueryWrapper = new QueryWrapper<>();
            carGoodsQueryWrapper.eq("car_id",shoppingCar.getCarId());
            List<ShoppingCarGoods> shoppingCarGoods = shoppingCarGoodsMapper.selectList(carGoodsQueryWrapper);
            BigDecimal total = BigDecimal.ZERO;
            BigDecimal goodsTotal;
            Order1 order1 = BeanUtil.copyProperties(param, Order1.class);
            order1.setStatus("UNPAY");
            order1.setCreateTime(new Date());
            long l = IdUtil.getSnowflake(1, 1).nextId();
            order1.setOrderNo(l);
            if (shoppingCarGoods.size()==0){
                throw new OstrichException(OstrichOrderServiceResultCode.NULL_ERROR);
            }
            for (ShoppingCarGoods carGoods :shoppingCarGoods) {
                GoodsDto goodsDto = goodsClient.getGoodsDto(carGoods.getGoodsId());
                goodsTotal = carGoods.getPrice().multiply(new BigDecimal(carGoods.getGoodsNum()));
                total=total.add(goodsTotal);
                RLock lock = redissonClient.getLock(carGoods.getGoodsId() + "");
                lock.lock(30,TimeUnit.SECONDS);
                PutGoodsParam putGoodsParam = new PutGoodsParam();
                putGoodsParam.setGoodsStock(goodsDto.getGoodsStock()-carGoods.getGoodsNum());
                if (putGoodsParam.getGoodsStock()<0){
                    throw new OstrichException(OstrichOrderServiceResultCode.NUMBER_ERROR);
                }
                putGoodsParam.setSales(goodsDto.getSales()+carGoods.getGoodsNum());
                putGoodsParam.setGoodsId(carGoods.getGoodsId());
                goodsClient.putGoods(putGoodsParam);
                OrderInfo orderInfo = BeanUtil.copyProperties(carGoods, OrderInfo.class);
                orderInfo.setOrderNo(l);
                int insert = orderInfoMapper.insert(orderInfo);
                if (insert<1){
                    throw new OstrichException(OstrichOrderServiceResultCode.ADD_ERROR);
                }
                lock.unlock();
            }
            order1.setTotalAmount(total);
            order1.setDeductionPrice(BigDecimal.ZERO);
            order1.setPayPrice(total.subtract(order1.getDeductionPrice()));


            int delete1 = shoppingCarMapper.delete(carQueryWrapper);
            int delete = shoppingCarGoodsMapper.delete(carGoodsQueryWrapper);
            if (delete<1||delete1<1){
                throw new OstrichException(OstrichOrderServiceResultCode.DEL_ERROR);
            }

            orderMapper.insert(order1);
            log.info(">>>>>>>>>>>直接冲");
            rocketMQTemplate.asyncSend("order", MessageBuilder.withPayload(order1).build(), new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    log.info("{}","异步成功");
                }
                @Override
                public void onException(Throwable throwable) {
                    log.info("{}>>>>>>>",throwable);
                }
            },3000L,7);
        }catch(Exception e){
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
        }

    }

    @Override
    public void cancelOrder(Long orderNo) throws TransactionException {
//        try {
        UpdateWrapper<Order1> wrapper = new UpdateWrapper<>();
        wrapper.eq("order_no",orderNo);
        Order1 order1 = orderMapper.selectOne(wrapper);
        if (order1.getStatus().equals("UNPAY")){
            wrapper.set("status","CANCEL");
            orderMapper.update(null,wrapper);
            QueryWrapper<OrderInfo> orderInfoQueryWrapper = new QueryWrapper<>();
            orderInfoQueryWrapper.eq("order_no",orderNo);
            List<OrderInfo> orderInfos = orderInfoMapper.selectList(orderInfoQueryWrapper);
//            // todo 修改用户余额
//            Result cusMessage = customerMangerClient.getCusMessage();
//            LinkedHashMap<String, Double> data = (LinkedHashMap<String, Double>) cusMessage.getData();
//            Double customerMoney = data.get("customerMoney");
//            BigDecimal cusMoney = new BigDecimal(customerMoney);
//            customerMangerClient.updateMoney(cusMoney.add(order1.getPayPrice()));
            for (OrderInfo orderInfo :orderInfos) {
                GoodsDto goodsDto = goodsClient.getGoodsDto(orderInfo.getGoodsId());
                PutGoodsParam putGoodsParam = new PutGoodsParam();
                putGoodsParam.setGoodsStock(goodsDto.getGoodsStock()+orderInfo.getGoodsNum());
                putGoodsParam.setGoodsId(orderInfo.getGoodsId());
                goodsClient.putGoods(putGoodsParam);

            }

//            int i = orderInfoMapper.delete(orderInfoQueryWrapper);
//            if (i<1){
//                throw new OstrichException(OstrichOrderServiceResultCode.DEL_ERROR);
//            }
        }


//        }catch(Exception e){
//            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
//        }

    }

    @Override
    public PageResult<ShoppingDto> searchOrder(Long orderNo,Integer current,Integer size) {
        QueryWrapper<Order1> wrapper = new QueryWrapper<>();
        wrapper.like("order_no",orderNo);
        PageResult<ShoppingDto> dto = null;
        Page<Order1> selectPage = orderMapper.selectPage(new Page<>(current, size), wrapper);
        if (selectPage!=null||selectPage.getRecords()!=null){
            List<ShoppingDto> shoppingDtos = BeanUtil.copyToList(selectPage.getRecords(), ShoppingDto.class);
            dto = new PageResult<>();
            dto.setElements(shoppingDtos);
            dto.setPage(selectPage.getCurrent());
            dto.setPageSize(selectPage.getSize());
            dto.setTotal(selectPage.getTotal());
            dto.setTotalPage(selectPage.getPages());
        }
        return dto;
    }

    @Override
    public String pay(Long orderNo,String url,Integer payType) {
        UpdateWrapper<Order1> wrapper = new UpdateWrapper<>();
        wrapper.eq("order_no",orderNo)
                .set("pay_type",payType);
        orderMapper.update(null,wrapper);
        Order1 order1 = orderMapper.selectOne(wrapper);
        BigDecimal payPrice = order1.getPayPrice();
        if (order1.getStatus().equals("CANCEL")){
            throw new RuntimeException("订单已取消");
        }
        if (order1.getShipType()==1){
            // todo 配送
            Result cusMessage = customerMangerClient.getCusMessage();
            LinkedHashMap<String, Integer> data = (LinkedHashMap<String, Integer>) cusMessage.getData();
            Long mobile = new Long(data.get("mobile"));
            OrderParam orderParam = new OrderParam();
            orderParam.setCustomerPhone(mobile);
            orderParam.setBusinessmanId(order1.getBusinessmanId());
            orderParam.setCreateTime(new Date());
            orderParam.setCustomerLocationId(order1.getCustomerLocationId());
            orderParam.setDeliveryNumber(order1.getOrderNo());
            log.info("orderParam>>>>>>>>{}",orderParam);
            deliveryOrderClient.orderAdd(orderParam);
        }else {
            order1.setQrCode(url);
        }
        if (order1.getPayType()==0){
            // todo 余额扣除
            Result cusMessage = customerMangerClient.getCusMessage();
            LinkedHashMap<String, Double> data = (LinkedHashMap<String, Double>) cusMessage.getData();
            Double customerMoney = data.get("customerMoney");
            BigDecimal cusMoney = new BigDecimal(customerMoney);

            if (cusMoney.compareTo(order1.getPayPrice()) < 0){
                    throw new OstrichException(OstrichOrderServiceResultCode.MONEY_ERROR);
                }
            Result result = customerMangerClient.updateMoney(cusMoney.subtract(order1.getPayPrice()));
            log.info("result>>>>>>>>{}",result.getData());
            order1.setStatus("PAY");
            order1.setPayTime(new Date());

            int update = orderMapper.update(order1, wrapper);
            AddSalesParam addSalesParam = new AddSalesParam();
            addSalesParam.setOrderNumber(orderNo);
            addSalesParam.setBusinessmanId(order1.getBusinessmanId());
            addSalesParam.setPayPrice(order1.getPayPrice());
            salesClient.addSales(addSalesParam);
            if (update<1){
                throw new OstrichException(OstrichOrderServiceResultCode.MODIFY_ERROR);
            }
            rocketMQTemplate.asyncSend("id", MessageBuilder.withPayload(order1).build(), new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    log.info("{}","异步成功");
                }
                @Override
                public void onException(Throwable throwable) {

                }
            });
            return "支付成功";

        }else {
            //todo 支付宝
            AliPay aliPay = new AliPay();
            aliPay.setTraceNo(orderNo+"");
            aliPay.setTotalAmount(payPrice);
            rocketMQTemplate.asyncSend("id", MessageBuilder.withPayload(order1).build(), new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    log.info("{}","异步成功");
                }
                @Override
                public void onException(Throwable throwable) {

                }
            });
            return payMoney(aliPay);
        }

    }

    @Override
    public String payMoney(AliPay aliPay) {
        AlipayTradePagePayResponse response;
        try {
            //  发起API调用（以创建当面付收款二维码为例）
            log.info("<<<<<<<{}",aliPay);
            response = Factory.Payment.Page()
                    .pay(URLEncoder.encode("xxx", "UTF-8"), aliPay.getTraceNo(), aliPay.getTotalAmount()+"", "");
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        return response.getBody();
    }

    @Override
    public void changeStatusByAliPay(String tradeNo) {
        long l = Long.parseLong(tradeNo);
        UpdateWrapper<Order1> wrapper = new UpdateWrapper<>();
        QueryWrapper<Order1> queryWrapper = new QueryWrapper<>();
        Order1 order1 = orderMapper.selectOne(queryWrapper);
        wrapper.eq("order_no",l);
        wrapper.set("status","PAY");
        wrapper.set("pay_time",new Date());
        AddSalesParam addSalesParam = new AddSalesParam();
        addSalesParam.setOrderNumber(l);
        addSalesParam.setBusinessmanId(order1.getBusinessmanId());
        addSalesParam.setPayPrice(order1.getPayPrice());
        salesClient.addSales(addSalesParam);
        orderMapper.update(null,wrapper);
    }

    @Override
    public String group(AddGroupParamInfra paramInfra) {
        Order1 order = BeanUtil.copyProperties(paramInfra, Order1.class);
        long l = IdUtil.getSnowflake(1, 1).nextId();
        order.setCreateTime(new Date());
        order.setShipType(1);
        order.setGroupbySn(paramInfra.getGroupbySn());
        order.setDeductionPrice(BigDecimal.ZERO);
        order.setPayPrice(paramInfra.getPrice());
        order.setTotalAmount(paramInfra.getTotalAmount());

        order.setDeductionPrice(paramInfra.getTotalAmount().subtract(paramInfra.getPrice()));
        order.setOrderNo(l);
        order.setPayType(1);
        GoodsDto goodsDto = goodsClient.getGoodsDto(paramInfra.getGoodsId());
        OrderInfo orderInfo = BeanUtil.copyProperties(goodsDto, OrderInfo.class);
        orderInfo.setOrderNo(l);
        orderInfo.setGoodsNum(1);
        orderInfo.setPrice(paramInfra.getPrice());
        int insert1 = orderInfoMapper.insert(orderInfo);
        int insert = orderMapper.insert(order);
        if (insert<1||insert1<1){
            throw new OstrichException(OstrichOrderServiceResultCode.ADD_ERROR);
        }
        //todo 支付宝
        AliPay aliPay = new AliPay();
        aliPay.setTraceNo(l+"");
        aliPay.setTotalAmount(paramInfra.getPrice());
        return payMoney(aliPay);
    }

    public void cancelGroup(Long orderNo){
        UpdateWrapper<Order1> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_no",orderNo);
        Order1 order1 = orderMapper.selectOne(updateWrapper);
        if (order1.getStatus().equals("UNPAY")){
            updateWrapper.set("status","CANCEL");
        }
    }

    public void cancelAllGroup(Integer groupbySn){
        QueryWrapper<Order1> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("groupby_sn",groupbySn);
        List<Order1> order1s = orderMapper.selectList(queryWrapper);
        for (Order1 order1 :order1s) {
            UpdateWrapper<Order1> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("order_no",order1.getOrderNo())
                         .set("status","CANCEL");
            orderMapper.update(null,updateWrapper);
            Result cusMessage = customerMangerClient.getCusMessage();
            LinkedHashMap<String, Double> data = (LinkedHashMap<String, Double>) cusMessage.getData();
            Double customerMoney = data.get("customerMoney");
            BigDecimal cusMoney = new BigDecimal(customerMoney);
            customerMangerClient.updateMoney(cusMoney.add(order1.getPayPrice()));
        }
    }

    @Override
    public PageResult<UserOrderDto> userFindAllOrder(int current,int size) {

        PageResult<UserOrderDto> dto = null;
        Page<Order1> selectPage = orderMapper.selectPage(new Page<Order1>(current, size), null);
        if (selectPage!=null||selectPage.getRecords()!=null){
            List<UserOrderDto> userOrderDtos = BeanUtil.copyToList(selectPage.getRecords(), UserOrderDto.class);
            dto = new PageResult<>();
            dto.setElements(userOrderDtos);
            dto.setPage(selectPage.getCurrent());
            dto.setPageSize(selectPage.getSize());
            dto.setTotal(selectPage.getTotal());
            dto.setTotalPage(selectPage.getPages());
        }
        return dto;
    }

    @Override
    public List<GroupCustomerDto> getGroupCustomer(Integer groupbySn) {
        QueryWrapper<Order1> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("groupby_sn",groupbySn);
        List<Order1> order1s = orderMapper.selectList(queryWrapper);
        List<GroupCustomerDto> integers = new ArrayList<>();
        for (Order1 order1 :order1s) {
            GroupCustomerDto groupCustomerDto = new GroupCustomerDto();
            groupCustomerDto.setCustomer(order1.getCustomerId());
            groupCustomerDto.setOrderNo(order1.getOrderNo());
            groupCustomerDto.setBusinessmanId(order1.getBusinessmanId());
            groupCustomerDto.setCustomerLocationId(order1.getCustomerLocationId());
            integers.add(groupCustomerDto);
        }
        return integers;
    }

    public void userCancelGroup(Long orderNo){
        UpdateWrapper<Order1> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_no",orderNo);
        Order1 order1 = orderMapper.selectOne(updateWrapper);
        updateWrapper.set("status","CANCEL");
        orderMapper.update(null,updateWrapper);
        // todo 库存

        Result cusMessage = customerMangerClient.getCusMessage();
        LinkedHashMap<String, Double> data = (LinkedHashMap<String, Double>) cusMessage.getData();
        Double customerMoney = data.get("customerMoney");
        BigDecimal cusMoney = new BigDecimal(customerMoney);
        customerMangerClient.updateMoney(cusMoney.add(order1.getPayPrice()));
    }

    @Override
    public OrderDto secKill(AddKillParamInfra paramInfra) {
        Order1 order = BeanUtil.copyProperties(paramInfra, Order1.class);
        order.setDeductionPrice(BigDecimal.ZERO);
        order.setPayPrice(paramInfra.getTotalAmount().subtract(order.getDeductionPrice()));
        order.setCreateTime(new Date());
        order.setShipType(1);
        long l = IdUtil.getSnowflake(1, 1).nextId();
        order.setOrderNo(l);
        GoodsDto goodsDto = goodsClient.getGoodsDto(paramInfra.getGoodsId());
        OrderInfo orderInfo = BeanUtil.copyProperties(goodsDto, OrderInfo.class);
        orderInfo.setPrice(paramInfra.getTotalAmount());
        orderInfo.setGoodsNum(1);
        orderInfo.setOrderNo(l);
        int insert1 = orderInfoMapper.insert(orderInfo);
        int insert = orderMapper.insert(order);
        if (insert<1||insert1<1){
            throw new OstrichException(OstrichOrderServiceResultCode.ADD_ERROR);
        }
        rocketMQTemplate.asyncSend("secKillOrder", MessageBuilder.withPayload(order).build(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("{}","异步成功");
            }
            @Override
            public void onException(Throwable throwable) {

            }
        },1000L,5);
        QueryWrapper<Order1> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no",l);
        Order1 order1 = orderMapper.selectOne(queryWrapper);
        log.info(">>>>>>>>>>>>>{}",order1.getOrderId());
        OrderDto orderDto = new OrderDto();
        orderDto.setOrderId(order1.getOrderId());
        return orderDto;
    }
    public void SecKillCancel(Long orderNo) throws Exception {
        UpdateWrapper<Order1> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_no",orderNo)
                     .set("status","CANCEL");
        QueryWrapper<Order1> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no",orderNo);
        Order1 order1 = orderMapper.selectOne(queryWrapper);
        if (order1.getStatus().equals("UNPAY")){
            orderMapper.update(null,updateWrapper);
            // todo 库存
            secKillClient.cancelSecKill(order1.getBusinessmanId(),order1.getOrderId());
        }

    }

    public void userCancelSecKill(Long orderNo) throws Exception {
        UpdateWrapper<Order1> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_no",orderNo);
        Order1 order = orderMapper.selectOne(updateWrapper);
        updateWrapper.set("status","CANCEL");
        orderMapper.update(null,updateWrapper);
        Result cusMessage = customerMangerClient.getCusMessage();
        LinkedHashMap<String, Double> data = (LinkedHashMap<String, Double>) cusMessage.getData();
        Double customerMoney = data.get("customerMoney");
        BigDecimal cusMoney = new BigDecimal(customerMoney);
        customerMangerClient.updateMoney(cusMoney.add(order.getPayPrice()));
        secKillClient.cancelSecKill(order.getBusinessmanId(),order.getOrderId());
    }
    @Override
    public void changeDeliveryInfo(Integer riderId, Integer deliveryId,Long orderNo) {
        UpdateWrapper<Order1> wrapper = new UpdateWrapper<>();
        wrapper.eq("order_no",orderNo);
        wrapper.set("rider_id",riderId);
        wrapper.set("delivery_id",deliveryId);
        int update = orderMapper.update(null, wrapper);
        if (update<1){
            throw new OstrichException(OstrichOrderServiceResultCode.MODIFY_ERROR);
        }
    }

    @Override
    public OrderAllGoods searchUserOrder(Long orderNo) {
        QueryWrapper<Order1> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no",orderNo);
        Order1 order = orderMapper.selectOne(queryWrapper);
        OrderAllGoods orderAllGoods = new OrderAllGoods();
        BeanUtil.copyProperties(order,orderAllGoods);
        QueryWrapper<OrderInfo> infoQueryWrapper = new QueryWrapper<>();
        infoQueryWrapper.eq("order_no",orderNo);
        List<OrderInfo> orderInfoList = orderInfoMapper.selectList(infoQueryWrapper);
        List<OrderGoods> orderGoods = BeanUtil.copyToList(orderInfoList, OrderGoods.class);
        orderAllGoods.setAllGoods(orderGoods);
        return orderAllGoods;
    }

    @Override
    public List<CustomerOrders> customerFindOrders(int parentId) {
        QueryWrapper<Order1> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_id",parentId);
        List<Order1> order1s = orderMapper.selectList(queryWrapper);
        if (order1s.size()==0){
            throw new OstrichException(OstrichOrderServiceResultCode.NULL_ERROR);
        }
        return BeanUtil.copyToList(order1s, CustomerOrders.class);
    }

    @Override
    public void changeOrderLocation(Long orderNo, Integer locationId) throws TransactionException {
//        try {
            UpdateWrapper<Order1> wrapper = new UpdateWrapper<>();
            wrapper.eq("order_no",orderNo)
                    .set("customer_location_id",locationId);
            orderMapper.update(null,wrapper);
//        }catch(Exception e){
//            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
//        }

    }

    @Override
    public PageResult<StoreOrderDto> StoreOrderFind(StoreOrderSearchParamInfra param) {
        QueryWrapper<Order1> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("businessman_id",param.getBusinessmanId())
                    .like(param.getOrderNo()!=null,"order_no",param.getOrderNo())
                    .between("create_time",param.getStartTime(),param.getFinishTime());
        PageResult<StoreOrderDto> dto = null;
        Page<Order1> selectPage = orderMapper.selectPage(new Page<>(param.getCurrent(), param.getSize()), queryWrapper);
        if (selectPage!=null||selectPage.getRecords()!=null){
            List<StoreOrderDto> StoreOrderDtos = BeanUtil.copyToList(selectPage.getRecords(), StoreOrderDto.class);
            dto = new PageResult<>();
            dto.setElements(StoreOrderDtos);
            dto.setPage(selectPage.getCurrent());
            dto.setPageSize(selectPage.getSize());
            dto.setTotal(selectPage.getTotal());
            dto.setTotalPage(selectPage.getPages());
        }
        return dto;
    }

    @Override
    public void userCancelOrder(Long orderNo) throws TransactionException {
//        try {
        QueryWrapper<Order1> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no",orderNo);
            Order1 order1 = orderMapper.selectOne(wrapper);
        UpdateWrapper<Order1> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_no",orderNo).set("status","CANCEL");
                orderMapper.update(null,updateWrapper);
                QueryWrapper<OrderInfo> orderInfoQueryWrapper = new QueryWrapper<>();
                orderInfoQueryWrapper.eq("order_no",orderNo);
                List<OrderInfo> orderInfos = orderInfoMapper.selectList(orderInfoQueryWrapper);
                // todo 修改用户余额
                Result cusMessage = customerMangerClient.getCustomerById(order1.getCustomerId());
                LinkedHashMap<String, Double> data = (LinkedHashMap<String, Double>) cusMessage.getData();
                Double customerMoney = data.get("customerMoney");
                BigDecimal cusMoney = new BigDecimal(customerMoney);
                customerMangerClient.updateMoney(cusMoney.add(order1.getPayPrice()));
                for (OrderInfo orderInfo :orderInfos) {
                    GoodsDto goodsDto = goodsClient.getGoodsDto(orderInfo.getGoodsId());
                    PutGoodsParam putGoodsParam = new PutGoodsParam();
                    putGoodsParam.setGoodsStock(goodsDto.getGoodsStock()+orderInfo.getGoodsNum());
                    putGoodsParam.setGoodsId(orderInfo.getGoodsId());
                    goodsClient.putGoods(putGoodsParam);

                }




//        }catch(Exception e){
//            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
//        }
    }

    @Override
    public void changeOrderStatusByStore(Long orderNo) {
        UpdateWrapper<Order1> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_no",orderNo)
                     .set("status","FINISHED");
        int update = orderMapper.update(null, updateWrapper);
        if (update<1){
            throw new OstrichException(OstrichOrderServiceResultCode.MODIFY_ERROR);
        }
    }

}
